<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div {
        width: 100px;
        height: 100px;
        background-color: orange;
        position: absolute;
        top: 0;
        left: 500px;
      }
      button {
        margin-top: 150px;
      }
      span {
        position: absolute;
        top: 0;
        left: 300px;
        width: 1px;
        height: 100px;
        background-color: black;
      }
    </style>
  </head>
  <body>
    <div></div>
    <span></span>
    <button>run</button>
    <script>
      const oDiv = document.querySelector("div");
      const button = document.querySelector("button");
      const spanEl = document.querySelector("span");
      const iSpeed = spanEl.offsetLeft - oDiv.offsetLeft > 0 ? 7 : -7;
      let timer = null;
      button.onclick = () => {
        startMove(oDiv, spanEl.offsetLeft);
      };

      function startMove(dom, target) {
        if (timer) {
          clearInterval(timer);
          timer = null;
        }
        timer = setInterval(function () {
          if (Math.abs(target - dom.offsetLeft) < Math.abs(iSpeed)) {
            // 停止
            clearInterval(timer);
            timer = null;
            dom.style.left = target + "px";
          } else {
            // 运动
            dom.style.left = dom.offsetLeft + iSpeed + "px";
          }
        }, 30);
      }
    </script>
  </body>
</html>
